package com.dandan.testcollection.httprequest;

import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import java.util.List;

/**
 * Created by Dandan on 2018/4/23.
 */

public class HttpApi {

    public static void generalRequest(@NonNull String url, @NonNull boolean isGet, Context context, List<String> params, List<String> values, @NonNull OnResponsListener onResponsListener) {
        if (TextUtils.isEmpty(url))
            return;
        HttpParams httpParams = new HttpParams();
        if (params != null && values != null) {
            for (int i = 0; i < params.size(); i++) {
                httpParams.put(params.get(i), values.get(i));
            }
        }

        if (isGet)
            getRequest(url, context, httpParams, onResponsListener);
        else
            postRequest(url, context, httpParams, onResponsListener);
    }

    private static void getRequest(String url, Context context, HttpParams httpParams, final OnResponsListener onResponsListener) {

        OkGo.<String>get(url).tag(context).params(httpParams).execute(new OnCallBackListener() {
            @Override
            public void onSuccess(Response<String> response) {
                onResponsListener.onSuccess(response.body());
            }

            @Override
            public void onError(Response<String> response) {
                try {
                    onResponsListener.onField(response.getException().getCause().toString());
                }
                catch (Exception e){}
            }
        });
    }

    private static void postRequest(String url, Context context, HttpParams httpParams, final OnResponsListener onResponsListener) {
        OkGo.<String>post(url).tag(context).params(httpParams).execute(new OnCallBackListener() {
            @Override
            public void onSuccess(Response<String> response) {
                onResponsListener.onSuccess(response.body());
            }

            @Override
            public void onError(Response<String> response) {
                try {
                    onResponsListener.onField(response.getException().getCause().toString());
                }
                catch (Exception e){}
            }
        });
    }

}
